/*
	Copyright (C) 2007 Joern Dinkla, www.dinkla.net, joern@dinkla.net

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package net.dinkla.emf;

import java.io.IOException;
import java.util.Collections;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.emf.codegen.ecore.Generator;


public class EMF {

	private static final String prefix = "PrefixCore";
	private static final String copyright = "Generated by mof2ecore by Joern Dinkla http://www.dinkla.net";
	private static final String modelName = "Core";
	private static final String modelDirectory = "/org.omg.cwm";
	private final static String extModel = ".ecore";
	private final static String extGen = ".genmodel";
	private final static String srcPath = "models";
	private final static String genPath = "generated/models";

	private ResourceSet resourceSet;
	private Diagnostician diagnostician;
	
	/**
	 * Initialize and add resource factory.
	 */
	public EMF() {
		Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl() {
	          public Resource createResource(URI uri)
	          {
	            XMIResource xmiResource = new XMIResourceImpl(uri);
	            return xmiResource;
	          }
	        });
			
		resourceSet = new ResourceSetImpl();
		resourceSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap());
	}

	/**
	 * Loads the ecore file.
	 */
	public Resource load(IPath path) {
		URI ecoreURI = URI.createFileURI(path.toString());
		Resource resource = resourceSet.getResource(ecoreURI, true);
		return resource;
	}

	/**
	 * @param path
	 * @return
	 */
	private Resource createGenModelResource(IPath path) {
		URI genModelURI = URI.createFileURI(path.toString());
        Resource resource = Resource.Factory.Registry.INSTANCE.getFactory(genModelURI).createResource(genModelURI);
        return resource;
	}

	/**
	 * Diagnose.
	 * 
	 * @param ePackage
	 */
	private Diagnostic diagnose(EPackage ePackage) {
        diagnostician = new Diagnostician();
        Diagnostic dg = diagnostician.validate(ePackage);
        System.out.println("dg=" + dg);
        return dg;
	}

	/**
	 * 
	 */
	private void run(String fileName) {


		IPath ecorePath = new Path(srcPath + "/" + fileName + extModel);
        IPath genModelPath = new Path(genPath + "/" + fileName + extGen);
        //IPath genModelPath = ecorePath.removeFileExtension().addFileExtension("genmodel");

        Resource resource = load(ecorePath);
		EPackage ePackage = (EPackage) resource.getContents().get(0);
        resource.setURI(URI.createURI(fileName + extModel));
        System.out.println("ep=" + ePackage);

        diagnose(ePackage);
        
        // generate .genmodel
        Resource genModelResource = createGenModelResource(genModelPath);
        
        GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
        genModelResource.getContents().add(genModel);
        resourceSet.getResources().add(genModelResource);

        // set the parameters
        genModel.setCopyrightText(copyright);
        genModel.setModelDirectory(modelDirectory);
        
        //genModel.getForeignModel().add(ecorePath.toString());
        genModel.getForeignModel().add(fileName);
        
        genModel.initialize(Collections.singleton(ePackage));
        //genModel.setModelName(genModelURI.trimFileExtension().lastSegment());
        genModel.setModelName(modelName);

        
        GenPackage genPackage = (GenPackage) genModel.getGenPackages().get(0);
        genPackage.setPrefix(prefix);
        
        try {
			genModelResource.save(Collections.EMPTY_MAP);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/* generate
		String[] arguments = new String[] {
				"",
				"models/cwm3.genmodel"
		};
		
		Generator generator = new Generator();
		generator.run(arguments);
		*/
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
        EMF emf = new EMF();
        emf.run("cwm_Core");
	}


}
